package com.chis.client;

import org.apache.commons.codec.binary.Base64;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class StreamUtil {
    public static String getStreamStr(String fileName) throws Exception {
        String r = null;
        byte[] bytes = null;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(5 * 1024 * 1024)) {
            try (ZipOutputStream zos = new ZipOutputStream(bos)) {
                InputStream is = StreamUtil.class.getResourceAsStream(fileName);
                if(is.available()>0) {
                    try (BufferedInputStream fileReader = new BufferedInputStream(is)) {
                        zos.putNextEntry(new ZipEntry(fileName));
                        byte[] b = new byte[1024];
                        int i;
                        while ((i = fileReader.read(b)) != -1) {
                            zos.write(b, 0, i);
                        }
                        zos.closeEntry();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            bytes = bos.toByteArray();
        }
        r = Base64.encodeBase64String(bytes);
        return r;
    }

    public static String compressAsBase64(InputStream is, String fileName) throws Exception {
        String r = null;
        byte[] bytes = null;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(5 * 1024 * 1024)) {
            try (ZipOutputStream zos = new ZipOutputStream(bos)) {
                if(is.available()>0) {
                    try (BufferedInputStream fileReader = new BufferedInputStream(is)) {
                        zos.putNextEntry(new ZipEntry(fileName));
                        byte[] b = new byte[1024];
                        int i;
                        while ((i = fileReader.read(b)) != -1) {
                            zos.write(b, 0, i);
                        }
                        zos.closeEntry();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            bytes = bos.toByteArray();
        }
        r = Base64.encodeBase64String(bytes);
        return r;
    }

    public  static InputStream getResource(String fileName){
        return StreamUtil.class.getResourceAsStream(fileName);
    }

}
